//
//  AppDelegate.m
//  Article
//
//  Created by LONG on 16/4/21.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "AppDelegate.h"
#import "LCTabBarController.h"
#import "LoginViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import <WXApi.h>
#import "JPUSHService.h"


#define JPushAppKey @"4a73bee1daacb2639051277d"
#define WXAppKey @"wx24f1f8198ba7b121"

@interface AppDelegate ()<WXApiDelegate,UIAlertViewDelegate>{
    int _num;
    int _apns;
}

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    self.window =[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //  self.window.rootViewController =[[LCTabBarController alloc]init];
    self.window.rootViewController = [[LoginViewController alloc]init];
    self.window.backgroundColor = [UIColor whiteColor];
    
    
    
    
    
    
    
    //极光推送
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_0
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |UIUserNotificationTypeSound | UIUserNotificationTypeAlert)     categories:nil];
    } else {
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)
#else
                                              categories:nil];
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)
#endif
                                              categories:nil];
    }
    _num = 0;
    _apns = 0;
    
    [JPUSHService setupWithOption:launchOptions appKey:JPushAppKey channel:nil apsForProduction:YES];
    
    if (launchOptions == nil) {
        
        NSLog(@"没有推送");
    }else{
//        NSNotification *mynotification = [NSNotification notificationWithName:@"icon" object:self userInfo:nil];
//        [[NSNotificationCenter defaultCenter] postNotification:mynotification];
//        
//        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"测试" message:@"123456789" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alertView show];
        NSLog(@"有推送");
        
    }
    
    
    
    
    //微信分享，向微信注册
    [WXApi registerApp:WXAppKey];
    
    
    //判断是否登陆，由登陆状态判断启动页面
    //获取UserDefault
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *token = [user objectForKey:@"token"];
    LCTabBarController *LCTabVC = [[LCTabBarController alloc]init];
    LoginViewController *loginVC = [[LoginViewController alloc]init];
    
    if (token == NULL) {
        self.window.rootViewController = loginVC;
    }else{
        NSUserDefaults *user =[NSUserDefaults standardUserDefaults];
        NSString * username = [NSString stringWithFormat:@"%@",[user objectForKey:@"mobile"]];
        NSString * password = [NSString stringWithFormat:@"%@",[user objectForKey:@"password"]];
        
        NSLog(@"%@",username);NSLog(@"%@",password);
        NSDictionary *useDic = @{@"mobile":username,
                                 @"password":password};
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        [manager POST:LOGIN_URL parameters:useDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            //[user setObject:[NSString stringWithFormat:@"%@",dic[@"status"]] forKey:@"status"];
            NSString *str = [[NSString alloc]initWithFormat:@"%@",dic[@"status"]];
            if ([str isEqualToString:@"1"]) {
                NSDictionary *dataDic = [[NSDictionary alloc]initWithDictionary:dic[@"data"]];
                if (![dataDic[@"user_token"] isEqualToString:[user objectForKey:@"token"]]) {
                    self.window.rootViewController = loginVC;
                    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"您的密码已被修改，请重新登录" message:@"" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alertView show];
                 
                }else{
                    
                    self.window.rootViewController = LCTabVC;
                    
                }
            }else{
                self.window.rootViewController = loginVC;
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"您的密码已被修改，请重新登录" message:@"" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
             
            }
        }
              failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  [self.window makeToast:@"网络连接失败，请检查网络连接" duration:0.5 position:CSToastPositionCenter];
              }];
        
        self.window.rootViewController = LCTabVC;
        
    }
    [self.window makeKeyAndVisible];
    
    
    

    
    return YES;
}


#pragma mark 微信代理

-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    
    BOOL canHandleURL = [Pingpp handleOpenURL:url withCompletion:nil];
    
    BOOL wxurl = [WXApi handleOpenURL:url delegate:self];
    
    if (canHandleURL) {
        return canHandleURL;
    }
    
    return wxurl;
}

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    
    BOOL canHandleURL = [Pingpp handleOpenURL:url withCompletion:nil];
    
    BOOL wxurl = [WXApi handleOpenURL:url delegate:self];
    
    if (canHandleURL) {
        return canHandleURL;
    }
    return wxurl;
}
-(void)onResp:(BaseResp *)resp{
    
    //把返回的类型转换成与发送时相对于的返回类型,这里为SendMessageToWXResp
    SendMessageToWXResp *sendResp = (SendMessageToWXResp *)resp;
    if (sendResp.errCode == 0) {
        NSLog(@"成功");
        //创建通知
        NSNotification *notification =[NSNotification notificationWithName:@"errCode" object:nil userInfo:nil];
        //通过通知中心发送通知
        [[NSNotificationCenter defaultCenter] postNotification:notification];
        
    }
    
    if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
        
    }
}


#pragma mark 极光
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    // Required
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
    [application registerForRemoteNotifications];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"DeviceToken 获取失败，原因：%@",error);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    NSLog(@"+++++++++++%@",userInfo);
    
    // Required
    [JPUSHService handleRemoteNotification:userInfo];
}
//- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
//    
//    //[[UIApplication sharedApplication] cancelLocalNotification:_mynotification];
//    
//    if (application.applicationState == UIApplicationStateInactive) {
//        NSLog(@"正在后台运行~");
//    }else{
//        NSLog(@"正在前台运行");
//    }
//}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@">>>>>>>>%@",userInfo);
    _apns = _apns + 1;
    if (userInfo) {
        if (_apns%2 == 0) {
            NSLog(@"%d",_apns);
        }else{
            NSNotification *mynotification = [NSNotification notificationWithName:@"backicon" object:self userInfo:nil];
            [[NSNotificationCenter defaultCenter] postNotification:mynotification];
            
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:[userInfo objectForKey:@"title"] message:[NSString stringWithFormat:@"%@",[userInfo objectForKey:@"content"] ] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
        
        
    }
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:_num + 1];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];   //清除角标
    [JPUSHService setBadge:0];
    [JPUSHService resetBadge];
    
    //[UMSocialSnsService  applicationDidBecomeActive];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
    //NSLog(@"角标个数：%ld",(long)[UIApplication sharedApplication].applicationIconBadgeNumber);
    if ((long)[UIApplication sharedApplication].applicationIconBadgeNumber == 0) {
        
    }else{
        NSLog(@"点击图标进入");
        NSNotification *mynotification = [NSNotification notificationWithName:@"icon" object:self userInfo:nil];
        [[NSNotificationCenter defaultCenter] postNotification:mynotification];
    }
    
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:_num + 1];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];   //清除角标
    [JPUSHService setBadge:0];
    [JPUSHService resetBadge];
    
//    //创建通知
//    NSNotification *notification =[NSNotification notificationWithName:@"errCode" object:nil userInfo:nil];
//    //通过通知中心发送通知
//    [[NSNotificationCenter defaultCenter] postNotification:notification];
    
}

#pragma mark alert代理
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//    if (buttonIndex == 0) {
//        
//    }else if (buttonIndex == 1){
//        NSLog(@"456");
//        NSNotification *mynotification = [NSNotification notificationWithName:@"backicon" object:self userInfo:@{@"where":@"YES"}];
//        [[NSNotificationCenter defaultCenter] postNotification:mynotification];
//    }
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
